/**
 * 在这里定义和用户相关的路由处理函数，供 /router/user.js 模块进行调用
 */
//导入数据库操作模块
var models = require('../db/index');
var mysql = require('mysql');

// 连接数据库
var conn = mysql.createConnection(models.mysql);
conn.connect();

// 新增题库
exports.addquestion = (req, res) => {
    /* 检测表单数据是否合法 */
    // 接收表单数据
    var body = req.body;
    // 查询是否有这个题目
    const sql = `select * from question where topic=?`;
    conn.query(sql, body.topic, function (err, results) {
        // 插入新题库到数据库
        if (err) return res.cc(err);
        const sql = `INSERT INTO question (qtype, qrection, week, difficulty, answer, topic, options) VALUES (?, ?, ?, ?, ?, ?, ?);`
        // const sql = `INSERT INTO question ?;`
        conn.query(sql, [body.qtype, body.qrection, body.week, body.difficulty, body.answer, body.topic, body.options], function (err, results) {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            // SQL 语句执行成功，但影响行数不为 1
            if (results.affectedRows !== 1) {
                return res.cc('新增题库失败，请稍后再试！');
            } else {
                return res.send({
                    status: 200,
                    message: '新增题库成功',
                })
            }
        })
    })
}

// 查询题库
exports.getQuestion = (req, res) => {
    var info = req.query;
    const sql = `select * from question`;
    conn.query(sql, info, (err, results) => {
        if (err) return res.cc(err);
        res.send({
            status: 200,
            data: results,
        })
    })
}

// 删除题库
exports.deleteQuestion = (req, res) => {
    var query = req.query;
    const sql = `delete from question where qid = ?;`;
    conn.query(sql, query.id, (err, results) => {
        if (err) return res.cc(err);
        res.send({
            status: 200,
            message: '删除成功'
        })
    })
}

//修改题库
exports.eqitQuestion = (req, res) => {
    var info = req.body;
    var body = req.params;
    console.log(info, 70, body);
    const sql = `update question set topic='${info.topic}',options='${info.options}',answer='${info.answer}' where qid=${body.id}`;
    conn.query(sql, (err, results) => {
        if (err) return res.cc(err);
        res.send({
            status: 200,
            message: '修改成功',
            data: results
        })
    })
}